package com.system.manager.modules.projectLibrary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.manager.common.annotation.CurrSubject;
import com.system.manager.common.entity.Result;
import com.system.manager.common.enums.ErrorCode;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.entity.User;
import com.system.manager.modules.authorized.mapper.UserMapper;
import com.system.manager.modules.projectLibrary.dto.ProjectLeaderDto;
import com.system.manager.modules.projectLibrary.dto.UsernamePassword;
import com.system.manager.modules.projectLibrary.entity.Enterprise;
import com.system.manager.modules.projectLibrary.entity.Project;
import com.system.manager.modules.projectLibrary.entity.ProjectLeader;
import com.system.manager.modules.projectLibrary.enums.ProjectLibraryErrorCode;
import com.system.manager.modules.projectLibrary.exception.ProjectLibraryException;
import com.system.manager.modules.projectLibrary.mapper.EnterpriseMapper;
import com.system.manager.modules.projectLibrary.mapper.ProjectLeaderMapper;
import com.system.manager.modules.projectLibrary.mapper.ProjectMapper;
import com.system.manager.modules.projectLibrary.service.IProjectLeaderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.manager.modules.projectLibrary.service.IProjectService;
import com.system.manager.modules.projectLibrary.vo.ProjectLeaderVo;
import com.system.manager.utils.MD5Utils;
import com.system.manager.utils.ThreadLocalMap;
import com.system.manager.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jisf
 * @since 2021-11-03
 */
@Service
public class ProjectLeaderServiceImpl extends ServiceImpl<ProjectLeaderMapper, ProjectLeader> implements IProjectLeaderService {

    @Autowired
    private ProjectLeaderMapper projectLeaderMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IProjectService iProjectService;

    /**
     * TODO 项目负责人注册个人信息
     *
     * @param projectLeaderVo
     * @return
     */
    @Override
    public UsernamePassword projectLeaderRegister(ProjectLeaderVo projectLeaderVo) {

        //获取前端传来的信息
        ProjectLeader projectLeader = new ProjectLeader();
        BeanUtils.copyProperties(projectLeaderVo, projectLeader);

        //设置用户名和密码
        String username = projectLeader.getName() + UUIDUtils.randomUUID().substring(0, 4);
        while (projectLeaderMapper.selectIdByUsername(username) != null) {   //名字重复时要防止生成的用户名重复
            username = projectLeader.getName() + UUIDUtils.randomUUID().substring(0, 4);
        }
        projectLeader.setUsername(username);
        if (projectLeader.getPassword() == null || projectLeader.getPassword().equals("")) {
            projectLeader.setPassword(UUIDUtils.randomUUID().substring(0, 8));
        }

        //获取公司名称获取对应的id
        Integer firm = enterpriseMapper.selectFirmIdByName(projectLeaderVo.getFirm());
        if (firm != null) {
            projectLeader.setFirm(firm);
        } else {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.FIRM_DOES_NOT_EXIST);
        }

        //获取项目名称和公司名称获取对应的id
        Integer project = projectMapper.selectProjectIdByName(projectLeaderVo.getProject(), firm);
        if (project != null) {
            projectLeader.setProject(project);
        }

        projectLeader.setActivate(0);   //未激活
        projectLeader.setRole(0);   //该角色为项目负责人

        //插入项目负责人信息
        try {
            projectLeaderMapper.insert(projectLeader);
        } catch (Exception e) {
            throw new SysException();
        }

        User user = new User();
        user.setUserAccount(projectLeader.getUsername());
        user.setPassword(MD5Utils.Base64Encode(projectLeader.getPassword()));
        user.setName(projectLeader.getName());
        user.setPhone(projectLeader.getPhone());
        user.setOrganizationId(projectLeader.getFirm());
        user.setStatus(0);
        user.setRole(3);
        try {
            userMapper.insert(user);
        }catch (Exception e){
            throw new SysException();
        }


        //返回用户名和密码
        Integer id = projectLeader.getId();
        if (id != null) {
            UsernamePassword usernamePassword = selectUsernamePassword(id);
            return usernamePassword;
        }
        return null;
    }

    /**
     * TODO 根据项目负责人id查询用户名密码
     *
     * @param id
     * @return
     */
    private UsernamePassword selectUsernamePassword(Integer id) {
        try {
            UsernamePassword usernamePassword = projectLeaderMapper.selectUsernamePasswordById(id);
            return usernamePassword;
        } catch (Exception e) {
            throw new ProjectLibraryException(ErrorCode.SYSTEM_FAILED);
        }
    }

    /**
     * TODO 修改用户信息
     *
     * @param projectLeader
     * @param subject
     */
    @Override
    public void updateProjectLeader(ProjectLeader projectLeader, Subject subject) {


        Integer id = subject.getId();
        User user = userMapper.selectById(id);
        String account = user.getUserAccount();

        QueryWrapper<ProjectLeader> queryWrapperProjectLeader = new QueryWrapper<>();
        queryWrapperProjectLeader.select("id").eq("username", account);
        Integer projectLeaderId = projectLeaderMapper.selectOne(queryWrapperProjectLeader).getId();
        if (projectLeaderId != projectLeader.getId()) {
            throw new ProjectLibraryException(ProjectLibraryErrorCode.USER_HAS_NO_PERMISSIONS);
        }


        //修改用户信息
        projectLeaderMapper.updateById(projectLeader);
    }

    /**
     * TODO 激活项目负责人
     *
     * @param id
     */
    @Override
    public void activateProjectLeader(Integer id) {

        //激活项目负责人
        UpdateWrapper<ProjectLeader> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("activate", 1).eq("id", id);
        projectLeaderMapper.update(new ProjectLeader(), updateWrapper);

    }

    /**
     * TODO 取消激活项目负责人
     *
     * @param id
     */
    @Override
    public void deactivateProjectLeader(Integer id) {

        //激活项目负责人
        UpdateWrapper<ProjectLeader> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("activate", 0).eq("id", id);
        projectLeaderMapper.update(new ProjectLeader(), updateWrapper);

    }

    /**
     * TODO 项目负责人取消分配
     *
     * @param id
     */
    @Override
    public String  assignProject(Integer id) {

        ProjectLeader projectLeader = projectLeaderMapper.selectById(id);
        Integer projectId = projectLeader.getProject();
        if(projectId == null){
            return "该员工没有负责的项目";
        }
        Project project = projectMapper.selectById(projectId);
        if(project.getPrincipal() != null && project.getPrincipal() == id){
            UpdateWrapper<Project> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("principal",null);
            updateWrapper.eq("id",project.getId());
            projectMapper.update(new Project(),updateWrapper);
        }

        UpdateWrapper<ProjectLeader> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("project",null);
        updateWrapper.eq("id",id);
        try {
            projectLeaderMapper.update(new ProjectLeader(),updateWrapper);
        }catch (Exception e){
            throw new SysException();
        }
        return "取消成功";
    }

    /**
     * TODO 查询项目负责人
     *
     * @param subject
     * @param activate
     * @return
     */
    @Override
    public Result selectProjectLeader(Subject subject, Integer page, Integer size, Integer activate, String name, Integer project, Integer whetherFree) {
        IPage<ProjectLeader> projectLeaderIPage = new Page<>(page,size);

        Integer firm = userMapper.selectById(subject.getId()).getOrganizationId();
        QueryWrapper<ProjectLeader> queryWrapper = new QueryWrapper<>();
        //查询本公司的项目负责人
        queryWrapper.eq("firm", firm);
        //根据是否激活来查询
        if (activate != null) {
            queryWrapper.eq("activate", activate);
        }
        //根据项目负责人姓名来查询
        if(name != null && !name.equals("")){
            queryWrapper.eq("name",name);
        }
        //根据所管理的项目来查询
        if(project != null){
            queryWrapper.eq("project",project);
        }
        //根据项目负责人是否空闲来查询
        if(whetherFree != null){
            if(whetherFree == 0){
                queryWrapper.isNull("project");
            }else {
                queryWrapper.isNotNull("project");
            }
        }
        page(projectLeaderIPage,queryWrapper);

        List<ProjectLeader> records = projectLeaderIPage.getRecords();
        List<ProjectLeaderDto> projectLeaderDtos = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            ProjectLeaderDto projectLeaderDto = new ProjectLeaderDto();
            ProjectLeader projectLeader = records.get(i);
            BeanUtils.copyProperties(projectLeader,projectLeaderDto);
            Integer id = projectLeader.getProject();
            String nameById = iProjectService.selectNameById(id);
            projectLeaderDto.setProject(nameById);
            projectLeaderDtos.add(projectLeaderDto);
        }

        int total = (int)projectLeaderIPage.getTotal();

        return Result.ok(projectLeaderDtos,total);
    }
}
